<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 警告 -->
    <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
    <!-- 步骤条 -->
    <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- 左边标签页 -->
    <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="80px" label-position="top">
      <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeleave" @tab-click="tabClick">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品分类" prop="goods_number">
            <el-cascader v-model="addForm.goods_cat" :options="categories" :props="categoriesProps" @change="CateHandleChange"></el-cascader>
          </el-form-item>
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="addForm.goods_price" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="addForm.goods_weight" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="addForm.goods_number" type="number"></el-input>
          </el-form-item>
        </el-tab-pane>
        <!-- 商品参数 -->
        <el-tab-pane label="商品参数" name="1">
          <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <!-- 商品属性 -->
        <el-tab-pane label="商品属性" name="2">
          <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <!-- 商品图片 -->
        <el-tab-pane label="商品图片" name="3">
          <el-upload action="http://127.0.0.1:8888/api/private/v1/upload" :headers="headersObj" list-type="picture" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-tab-pane>
        <!-- 商品内容 -->
        <el-tab-pane label="商品内容" name="4">
          <!-- 富文本编辑器组件 -->
          <quill-editor v-model="addForm.goods_introduce" class="quillEditor"></quill-editor>
          <!-- 添加商品的按钮 -->
          <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <!-- 对话框 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%" @close="dialogClose">
      <img :src="previewPath" class="imgwidth" />
    </el-dialog>
  </div>
</template>

<script>
import loginVue from '../login.vue'
export default {
  created() {
    this.getCategories()
  },
  data() {
    return {
      activeIndex: '0',// 双向绑定标签页跟步骤条
      addForm: {//表单数据
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [1, 3, 6],
        pics: [],
        // 商品的详情描述
        goods_introduce: '',
        attrs: [],
      },
      addFormRules: {//表单验证规则
        goods_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
      },
      categories: [],//商品分类数据
      categoriesProps: {//级联选择器props参数
        expandTrigger: 'hover',
        children: 'children',
        label: 'cat_name',
        value: 'cat_id',
      },
      manyTableData: [],// 动态参数列表数据
      onlyTableData: [],// 静态参数列表数据
      headersObj: {//上传图片的请求头部
        Authorization: window.sessionStorage.getItem('token')
      },
      dialogVisible: false,//控制图片对话框开启关闭
      picurll: '',//图片实际在线地址
      previewPath: '',
    }
  },
  methods: {
    //   获取商品分类
    getCategories() {
      this.$http.get('categories').then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error('获取商品分类失败')
        }
        this.categories = res.data.data
      })
    },
    //级联选择器改变
    CateHandleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // tabs离开属性方法传新老标签
    beforeleave(activeName, oldActiveName) {
      if (oldActiveName == 0 && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择三级分类')
        return false
      }
    },
    // 点击标签页触发函数
    tabClick() {
      if (this.activeIndex == '1') {
        this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        ).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error('获取动态参数列表失败！')
          }
          res.data.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          });
          this.manyTableData = res.data.data
          console.log(this.manyTableData, 'manyTableData');
        })
      } else if (this.activeIndex == '2') {
        this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } }).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error('获取静态参数列表失败！')
          }
          this.onlyTableData = res.data.data
          console.log(this.onlyTableData, 'onlyTableData');
        })
      }
    },
    // 点击图片名称执行的函数
    handlePreview(file) {
      this.previewPath = file.response.data.url
      console.log(this.previewPath);
      this.dialogVisible = true
    },
    // 图片移除
    handleRemove(file) {
      console.log(file, 'file');
      const i = this.addForm.pics.findIndex(pic => {
        return pic.pic == file.response.data.tmp_path
      })
      this.addForm.pics.splice(i, 1)
    },
    // 图片文件上传成功后的勾子
    handleSuccess(response) {
      console.log(response, '图片上传成功响应');
      const pic = { "pic": response.data.tmp_path }
      this.addForm.pics.push(pic)
    },
    //关闭图片清空previewPath防止打开新图片后旧图片还存在
    dialogClose() {
      this.previewPath = ''
    },
    // 添加
    add() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项！')
        }
        // 深拷贝
        const newAddForm = JSON.parse(JSON.stringify(this.addForm));
        newAddForm.goods_cat = newAddForm.goods_cat.join(',')
        var attrs = this.manyTableData.concat(this.onlyTableData)
        newAddForm.attrs = attrs
        this.$http.post('goods', newAddForm).then(res => {
          if (res.data.meta.status !== 201) {
            return this.$message.error(res.data.meta.msg)
          }
          this.$message.success('商品创建成功')
          console.log(res);
        })

      })
    }
  },
  computed: {
    //   第三级分类的id
    cateId() {
      return this.addForm.goods_cat[2]
    }
  }
}
</script>

<style scoped>
.el-steps {
  margin: 15px 0;
}
/deep/ .el-step__title {
  font-size: 13px;
}
.imgwidth {
  max-width: 100%;
}
.btnAdd {
  margin-top: 15px;
}
/deep/ .ql-editor {
  min-height: 300px;
}
</style>